package org.liquidByte.trafficMustang.androidApp;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class Config {
	
	public static final String DEFAULT_CONTEXT_ROOT = "http://10.0.0.104:8080/businessServer/resources";
	public static final String CONTEXT_ROOT_KEY = "contextRoot";
	
	private static Config instance;
	
	public static Config getInstance() {
		return Config.instance;
	}
	public static void create(Context ctx) {
		Config.instance = new Config(ctx);
	}
	
	private SharedPreferences prefs;
	private PreferencesChanged changedActionListener;
	private final Context context;
	
	private Config(Context ctx){
		if (ctx == null) {
			throw new IllegalArgumentException("ctx is null");
		}
		this.context = ctx;
	}

	
	public void setChangedActionListener(PreferencesChanged changedActionListener) {
		this.changedActionListener = changedActionListener;
	}
	protected SharedPreferences getPrefs() {
		if (this.prefs == null) {
			this.prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
			this.prefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
				@Override
				public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
					Config.this.setPrefs(sharedPreferences);
				}
			});
		}
		return prefs;
	}
	protected synchronized void setPrefs(SharedPreferences prefs) {
		this.prefs = prefs;
		if (this.changedActionListener != null) {
			this.changedActionListener.onChanged(this);
		}
	}
	public String getContextRoot() {
		return this.getPrefs().getString(CONTEXT_ROOT_KEY, DEFAULT_CONTEXT_ROOT);
	}
	public void setContextRoot(String value) {
		SharedPreferences preferences = this.getPrefs();
		SharedPreferences.Editor edit = preferences.edit();
		if (value == null || value.equals("")) {
			edit.remove(CONTEXT_ROOT_KEY);
		} else {
			edit.putString(CONTEXT_ROOT_KEY, value);
		}
		edit.commit();
	}
	
	public interface PreferencesChanged {
		void onChanged(Config config);
	}
}
